package com.bestv.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * 上传文件
 * User: Henry
 * Date: 14-5-6
 */
public class UploadServlet extends HttpServlet {
    private Logger logger = LoggerFactory.getLogger(getClass());

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        String strXML = GenerateUploader(request, response);
        PrintWriter writer = response.getWriter();
        writer.append(strXML);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        String strXML = GenerateUploader(request, response);
        PrintWriter writer = response.getWriter();
        writer.append(strXML);
    }

    private String GenerateUploader(HttpServletRequest request, HttpServletResponse response) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 1024); // 设置缓存的大小
        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            logger.error("Error on parsing request.", e);
        }

        for (FileItem item : items) {
            // 处理非上传文件框
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                request.setAttribute(name, value);
                continue;
            }

            // 获取上传文件名
            String value = item.getName();
            int start = value.lastIndexOf("\\");
            String fileName = value.substring(start + 1);

            // 创建上传文件
            File uploadDir = new File("/tmp/upload");
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            File uploadFile = new File(uploadDir, fileName);

            int length;
            byte[] buffer = new byte[1024];
            OutputStream out;
            InputStream in;
            try {
                out = new FileOutputStream(uploadFile);
                in = item.getInputStream();
                while ((length=in.read(buffer)) != -1) {
                    out.write(buffer, 0, length);
                }
                in.close();
                out.close();
            } catch (FileNotFoundException e) {
                logger.error("File not found.", e);
            } catch (IOException e) {
                logger.error("Error on input & output.", e);
            }
        }
        return "上传文件成功!";
    }
}
